package com.hertz.iris.core;

import javax.inject.Inject;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;

import com.hertz.iris.IrisApplication;
import com.hertz.iris.IrisServiceProvider;
import com.hertz.iris.util.Constants;
import com.hertz.iris.util.DateUtil;
import com.hertz.iris.util.Ln;
import com.hertz.iris.view.alert.MatchAlarmRec;

public class TriggerService {
	
	@Inject IrisServiceProvider serviceProvider;
	
	@Inject
	public TriggerService(){}
	
	public void matchAlarmAlertTrigger(long nextTime){
		AlarmManager am = (AlarmManager) IrisApplication.getInstance().getSystemService(Context.ALARM_SERVICE);  
		Intent intent = new Intent(Constants.MATCH_ALARM_ACTION);  
		intent.setClass(IrisApplication.getInstance().getApplicationContext(), MatchAlarmRec.class);  
		String ymd = DateUtil.today("yyyyMMdd");
		PendingIntent sender = PendingIntent.getBroadcast(IrisApplication.getInstance().getApplicationContext(), Integer.valueOf(ymd), intent, PendingIntent.FLAG_CANCEL_CURRENT);
		am.set(AlarmManager.RTC_WAKEUP, nextTime, sender); 
		
	}
	
	public boolean getTrrigerIsRunning(Context context){
    	SharedPreferences sharedPreferences = context.getSharedPreferences(Constants.MyPreference.PREFERENCE_NAME, Context.MODE_PRIVATE);
    	Boolean isRunning = sharedPreferences.getBoolean(Constants.MyPreference.SERVICE_RUNNING, false);
    	Ln.d("SERVICE_RUNNING = %s", isRunning);
    	return isRunning;
    }
    
    public void setTrrigerRunning(boolean value,Context context){
    	Ln.d("setRunning", "%s",value);
    	SharedPreferences sp = context.getSharedPreferences(Constants.MyPreference.PREFERENCE_NAME, Context.MODE_PRIVATE);
    	SharedPreferences.Editor editor = sp.edit();
    	editor.putBoolean(Constants.MyPreference.SERVICE_RUNNING, value);
//    	if(value){
//    		editor.putLong(Constants.MyPreference.LAST_TRIGGER, System.currentTimeMillis());
//    	}
    	boolean result = editor.commit();
    	if(!result){
    		Ln.e("commit preference fault");
    	}
    }
}
